package com.atguigu.system.controller;


import com.atguigu.admin.model.entity.SysUser;
import com.atguigu.admin.service.SysUserService;
import com.atguigu.common.result.Result;
import com.atguigu.common.utils.JwtUtils;
import com.atguigu.system.model.entity.InventoryFlow;
import com.atguigu.system.model.entity.InventoryInfo;
import com.atguigu.system.model.entity.PurchaseManagement;
import com.atguigu.system.service.InventoryFlowService;
import com.atguigu.system.service.InventoryInfoService;
import com.atguigu.system.service.PurchaseManagementService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

/**
 * <p>
 *  订单管理
 * </p>
 *
 * @author 
 * @since 2025-03-02
 */
@RestController
@RequestMapping("/system/purchase-management")
public class PurchaseManagementController {

    @Autowired
    private PurchaseManagementService purchaseManagementService;


    @Autowired
    private InventoryFlowService inventoryFlowService;

    @Autowired
    private SysUserService sysUserService;


    @Autowired
    private InventoryInfoService inventoryInfoService;

    // 新增采购记录
    @PostMapping("/save")
    public Result<?> savePurchase(@RequestBody PurchaseManagement purchase,HttpServletRequest request) {
        BigDecimal unitPrice = purchase.getUnitPrice();
        Integer purchaseQuantity = purchase.getPurchaseQuantity();
        BigDecimal quantityAsBigDecimal = new BigDecimal(purchaseQuantity);
        BigDecimal sum = unitPrice.multiply(quantityAsBigDecimal);
        purchase.setTotalAmount(sum);

        String purchaseStatus = purchase.getPurchaseStatus();
        if (purchaseStatus.equals("已入库")){
            extracted(purchase,request);
        }

        boolean save = purchaseManagementService.save(purchase);
        if (save) {
            return Result.ok();
        } else {
            return Result.fail("新增采购记录失败");
        }
    }

    // 根据 ID 删除采购记录（逻辑删除）
    @DeleteMapping("/delete/{id}")
    public Result<?> deletePurchase(@PathVariable Integer id) {
        boolean update = purchaseManagementService.removeById(id);
        if (update) {
            return Result.ok();
        } else {
            return Result.fail("删除采购记录失败");
        }
    }

    // 根据 ID 更新采购记录
    @PutMapping("/update")
    public Result<?> updatePurchase(@RequestBody PurchaseManagement purchase,HttpServletRequest request) {
        BigDecimal unitPrice = purchase.getUnitPrice();
        Integer purchaseQuantity = purchase.getPurchaseQuantity();
        BigDecimal quantityAsBigDecimal = new BigDecimal(purchaseQuantity);
        BigDecimal sum = unitPrice.multiply(quantityAsBigDecimal);
        purchase.setTotalAmount(sum);

        // 商品进行入库
        String purchaseStatus = purchase.getPurchaseStatus();
        if (purchaseStatus.equals("已入库")){
            extracted(purchase,request);
        }

        boolean update = purchaseManagementService.updateById(purchase);
        if (update) {
            return Result.ok();
        } else {
            return Result.fail("更新采购记录失败");
        }
    }


    private void extracted(PurchaseManagement purchase, HttpServletRequest request) {
        String userId = JwtUtils.getUserId(request.getHeader("token"));
        SysUser byId = sysUserService.getById(userId);
        InventoryFlow inventoryFlow = new InventoryFlow();
        inventoryFlow.setOperatorId(Math.toIntExact(byId.getId()));
        inventoryFlow.setOperatorName(byId.getName());
        inventoryFlow.setChangeQuantity(purchase.getPurchaseQuantity());

        LambdaQueryWrapper<InventoryInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(InventoryInfo::getSkuId, purchase.getProductId());
        InventoryInfo one = inventoryInfoService.getOne(queryWrapper);
        Integer purchaseQuantity = purchase.getPurchaseQuantity();
        Integer currentStock = one.getCurrentStock();
        one.setCurrentStock(purchaseQuantity+currentStock);
        inventoryInfoService.updateById(one);

        inventoryFlow.setInventoryId(one.getSkuId());
        inventoryFlow.setOperationType("入库");
        inventoryFlow.setOperationReason("订单入库");
        inventoryFlowService.getBaseMapper().insert(inventoryFlow);
    }

    // 根据 ID 查询采购记录
    @GetMapping("/get/{id}")
    public Result<?> getPurchase(@PathVariable Integer id) {
        PurchaseManagement purchase = purchaseManagementService.getById(id);
        if (purchase != null) {
            return Result.ok(purchase);
        } else {
            return Result.fail("未找到该采购记录");
        }
    }

    // 分页查询采购记录，支持根据供应商 ID、商品 ID 和采购状态筛选
    @GetMapping("/page")
    public Result<?> pageQuery(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "10") Integer pageSize,
                               @RequestParam(required = false) Integer supplierId,
                               @RequestParam(required = false) Integer productId,
                               @RequestParam(required = false) String purchaseStatus) {
        Page<PurchaseManagement> page = new Page<>(pageNum, pageSize);
        Page<PurchaseManagement> resultPage = purchaseManagementService.pageQuery(page, supplierId, productId, purchaseStatus);
        return Result.ok(resultPage);
    }
}

